<?php

/**
 * SQL查询结果文件缓存
 * @description Holp You Do Good But Not Evil
 * @copyright   Copyright 2014-2015 <ycchen@iwshop.cn>
 * @license     LGPL (http://www.gnu.org/licenses/lgpl.html)
 * @author      Chenyong Cai <ycchen@iwshop.cn>
 * @package     Wshop
 * @link        http://www.iwshop.cn
 */

class SqlCached extends Model {

    // 缓存5秒
    const EXP = 2;

    /**
     * 
     * @param type $k
     * @return type
     */
    private function genKey($k) {
        return hash('md4', $k . APPID . 'xa123d');
    }

    /**
     * 
     * @param type $k
     * @return type
     */
    public function get($k, $exp = false) {
        $fn = $this->genKey($k);
        if(!$exp){
            $exp = self::EXP;
        }
        $f = dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . 'sql_cache' . DIRECTORY_SEPARATOR . $fn . '.sqlc';
        if (is_file($f) && (time() - filemtime($f)) < $exp) {
            return unserialize(base64_decode(file_get_contents($f)));
        } else {
            @unlink($f);
            return -1;
        }
    }

    /**
     * 
     * @param type $k
     * @param type $v
     * @return boolean
     */
    public function set($k, $v) {
        $fn = $this->genKey($k);
        $f = dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . 'sql_cache' . DIRECTORY_SEPARATOR . $fn . '.sqlc';
        file_put_contents($f, base64_encode(serialize($v)));
        return true;
    }

}
